import React, { memo, useEffect, useState } from 'react';
import { Table, message } from 'antd';
import { isArrayWithLength } from '@/utils';
import { TableWarpper } from './style.js'


const Index = memo((props) => {
    const { columns, api, params = {}, data, showPagination = true } = props
    const [tableData, setTableData] = useState([])
    const [tableLoading, setTableLoading] = useState(false)
    const [total, setTotal] = useState(false)
    async function fetchTableData(page = 1, size = 10) {
        setTableLoading(true)
        try {
            if (isArrayWithLength(data) || !api) return
            const res = await api({ pageIndex: page, pageSize: size, ...params })
            setTableData(res.data.items)
            setTotal(res.data.total)
        } catch (error) {
            messageApi.open({
                type: 'error',
                content: error || error.msg || "系统出错",
            });
        } finally {
            setTableLoading(false)
        }
    }
    useEffect(() => {
        if (isArrayWithLength(data)) {
            setTableData(data)
        } else if (api) {
            fetchTableData()
        }
    }, [data])
    function onPageChange(page, size) {
        fetchTableData(page, size)
    }
    return (
        <TableWarpper>
            <Table sticky={true} columns={columns} dataSource={tableData} loading={tableLoading} size='small' pagination={showPagination && { size: "small", defaultCurrent: 1, onChange: onPageChange, total: total }} />
        </TableWarpper>
    )
})


export default Index;